package com.example.forumsystem.controller;

import com.example.forumsystem.common.AppResult;
import com.example.forumsystem.common.ResultCode;
import com.example.forumsystem.config.AppConfig;
import com.example.forumsystem.exception.ApplicationException;
import com.example.forumsystem.model.Article;
import com.example.forumsystem.model.User;
import com.example.forumsystem.services.IArticleService;
import com.example.forumsystem.services.IBoardService;
import com.example.forumsystem.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpLogging;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Api(tags = "文章相关接口")
@RestController
@Slf4j
@RequestMapping("/article")
public class ArticleController {

    @Resource
    IArticleService articleService;


    @ApiOperation("发布文章")
    @PostMapping("/create")
    public AppResult createArticle(HttpServletRequest request,
                                   @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                                   @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                                   @ApiParam("文章正文") @RequestParam("content") @NonNull String content) {
        // 参数合法性校验
        if(boardId <= 0) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "boardId" + boardId);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        // 获取登入用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户权限
        if (user.getState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_BANNED.toString() + "userName" + user.getUserName());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
//
//        // 修改板块文章数量
//        boardService.addOneArticleCountById(boardId);
//
//        // 修改用户文章数量
//        userService.addOneArticleCountById(user.getId());


        Article article = new Article();
        article.setTitle(title);            // 文章标题
        article.setContent(content);        // 文章正文
        article.setBoardId(boardId);        // 板块id
        article.setUserId(user.getId());    // 关联userId

        // 新增文章
        articleService.creaete(article);

        return AppResult.success();
    }

    @ApiOperation("获取全部未删除的文章")
    @GetMapping("/getAllByBoardList")
    public AppResult<List<Article>> getAllByBoardList(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles;

        if(boardId == null) {
            // 调用DAO
            articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        // 校验是否为空
        if(articles == null) {
            articles = new ArrayList<>();
        }

        return AppResult.success(articles);
    }

    @ApiOperation("根据id获取文章详情")
    @GetMapping("/details")
    public AppResult getDetails(HttpServletRequest request ,@ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        // 调用 service 查询
        Article article = articleService.selectDetailById(id);
        // 返回值校验
        if(article == null) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 获取session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验是否是作者
        if(user.getId() == article.getUserId()) {
            article.setOwn(true);
        }

        return AppResult.success(article);
    }

    @PostMapping("/modify")
    @ApiOperation("修改文章")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("文章id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("文章标题") @RequestParam("title")  @NonNull String title,
                            @ApiParam("文章正文") @RequestParam("content") @NonNull String content) {
        log.info("接受到修改请求");
        // 获取session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 校验用户权限
        if(user.getState() == 1 || user.getDeleteState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 根据文章id获取文章信息
        Article article = articleService.selectById(id);

        log.info("article.getDeleteState()" + article.getDeleteState());
        log.info("article.getState()" + article.getState());
        // 校验文章权限
        if(article.getDeleteState() == 1 || article.getState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 校验是否是作者

        if(user.getId() != article.getUserId()) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_UNAUTHORIZED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_USER_UNAUTHORIZED);
        }

        // 调用 service 修改文章
        articleService.modify(id,title,content);
        log.info("更新文章成功, 文章标题: " + article.getTitle() + " , 用户id: " + user.getId());
        return AppResult.success();
    }

    @PostMapping("/thumbsUp")
    @ApiOperation("点赞")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {

        // 获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if(user.getState() == 1 || user.getDeleteState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 获取文章信息
        Article article = articleService.selectById(id);
        // 校验文章状态
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        articleService.thumbsUpById(id);

        return AppResult.success();
    }

    @PostMapping("/delete")
    @ApiOperation("删除文章")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        // 获取用户信息
        HttpSession session = request.getSession(false);

        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if(user.getState() == 1 || user.getDeleteState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 获取文章信息
        Article article = articleService.selectById(id);
        // 校验文章状态
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 调用service删除文章
        articleService.subOneArticleCountById(id);
        log.info("删除文章成功, articleId: " + id);
        return AppResult.success();
    }

    @ApiOperation("查询用户的所有文章")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                               @ApiParam("用户id") @RequestParam(value = "userId", required = false) Long userId) {

        log.info("接收到达userId = " + userId);
        // 校验是否为空
        if(userId == null) {
            // 获取当前登入用户的文章
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }

        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
